// 递增最大的整数
// 从前向后
; (function () {
    return
    /**
   * @param {number} n
   * @return {number}
   */
    var monotoneIncreasingDigits = function (n) {

        if (n < 10) return n
        let str = '' + n
        let start = str[0]
        let number = str[0]
        let flag = true
        for (let i = 1; i < str.length; i++) {
            num = str[i];

            if (num >= start && flag) {
                // 说明还在递增
                number += num
                start = num
            } else {

                // 已经不在递增了
                // 考虑到当前的num可能重复
                //  再次判断一下
                // 应该找到所有和start相同的

                if (start === str[i - 2] && flag) {
                    let count = 0;
                    let index = 0;

                    while ((index = number.indexOf(start, index)) !== -1) {
                        count++;
                        index++
                    }
                    // 66888 变成 66800
                    // 99999 变成 90000
                    number = number.slice(0, -1 * count) + start * Math.pow(10, count - 1)
                    console.log(count, number);
                }
                flag = false
                number += 0
            }

        }



        return flag ? Number(number) : Number(number) - 1
    };
    console.log(monotoneIncreasingDigits(132))
    console.log(monotoneIncreasingDigits(6688841))
    console.log(monotoneIncreasingDigits(999998))
    console.log(monotoneIncreasingDigits(777616726))






})();

// 从后向前 方法更简单
; (function () {
    //return
    var monotoneIncreasingDigits = function (n) {
        if (n < 10) return n
        let str = '' + n
        let len = str.length-1
        let end = str[len]
        let number = str
        let flag = true
        for (let i = len-1; i >=0; i--) {
           let  curNum = str[i];
           if(curNum>end){
            flag=false
            end = curNum-1
            number = number.slice(0,i)+curNum * Math.pow(10, len-i )
           }else{
            end = curNum
           }
        }
        return flag ? Number(number) : Number(number) - 1
    }

    console.log(monotoneIncreasingDigits(101))
    // console.log(monotoneIncreasingDigits(132))
    // console.log(monotoneIncreasingDigits(6688841))
    // console.log(monotoneIncreasingDigits(999998))
    // console.log(monotoneIncreasingDigits(777616726))
})();